import 'package:flutter/material.dart';
import 'package:loading_more_list/loading_more_list.dart';

import 'list_indicator.dart';

typedef Widget ItemBuilder<T>(BuildContext context, T item, int index);

class CustomLoadingMoreList<T> extends StatefulWidget {
  final LoadingMoreBase<T> loadingMoreBase;

  final ItemBuilder<T> itemBuilder;

  final EdgeInsetsGeometry padding;

  final ScrollController? controller;

  final ExtendedListDelegate? extendedListDelegate;

  final bool isSliver;

  final ScrollPhysics? physics;

  final LoadingMoreIndicatorBuilder? indicatorBuilder;

  final SliverGridDelegate? gridDelegate;

  final Widget? noMoreChildWidget;
  final Widget? emptyChildWidget;

  final bool shrinkWrap;

  const CustomLoadingMoreList(
    this.itemBuilder,
    this.loadingMoreBase, {
    Key? key,
    this.padding = const EdgeInsets.all(0),
    this.extendedListDelegate,
    this.isSliver = false,
    this.physics,
    this.indicatorBuilder,
    this.gridDelegate,
    this.noMoreChildWidget,
    this.emptyChildWidget,
    this.shrinkWrap: false,
    this.controller,
  }) : super(key: key);

  @override
  _CustomLoadingMoreListState<T> createState() =>
      _CustomLoadingMoreListState<T>();
}

class _CustomLoadingMoreListState<T> extends State<CustomLoadingMoreList<T>> {
  @override
  Widget build(BuildContext context) {
    Widget child;
    if (!widget.isSliver) {
      child = LoadingMoreList(
        ListConfig<T>(
          itemBuilder: widget.itemBuilder,
          sourceList: widget.loadingMoreBase,
          padding: widget.padding,
          controller: widget.controller,
          physics: widget.physics,
          shrinkWrap: widget.shrinkWrap,
          indicatorBuilder: widget.indicatorBuilder ??
              (BuildContext context, IndicatorStatus indicatorStatus) {
                return ListIndicator(
                  indicatorStatus,
                  widget.loadingMoreBase,
                  noMoreChildWidget: widget.noMoreChildWidget,
                );
              },
          extendedListDelegate: widget.extendedListDelegate,
          gridDelegate: widget.gridDelegate,
          addAutomaticKeepAlives: true,
        ),
      );
    } else {
      child = LoadingMoreSliverList(
        SliverListConfig<T>(
          itemBuilder: widget.itemBuilder,
          sourceList: widget.loadingMoreBase,
          padding: widget.padding,
          extendedListDelegate: widget.extendedListDelegate,
          gridDelegate: widget.gridDelegate,
          indicatorBuilder: widget.indicatorBuilder ??
              (BuildContext context, IndicatorStatus indicatorStatus) {
                return ListIndicator(
                  indicatorStatus,
                  widget.loadingMoreBase,
                  isSliver: true,
                  noMoreChildWidget: widget.noMoreChildWidget,
                    emptyChildWidget:widget.emptyChildWidget,
                );
              },
        ),
      );
    }
    return child;
  }
}
